import 'dart:convert';

import 'package:dio/dio.dart';

import 'package:heven/api/encryption.dart';
import 'package:heven/api/encryption1.dart';
import 'package:heven/model/user_model.dart';
import 'package:heven/utils/index.dart';

/// dio网络请求配置表 自定义
class DioConfig {
  static const baseURL = 'https://ai-pre.api.hevensmart.com';
  //'https://ai.api.hevensmart.com'; //域名 https://ai-pre.api.hevensmart.com
  static Duration timeout = const Duration(seconds: 15000); //超时时间
}

// 网络请求工具类
class DioRequest {
  late Dio dio;

  /// 构造函数
  DioRequest() {
    dio = Dio();
    dio.options = BaseOptions(
      baseUrl: DioConfig.baseURL,
      connectTimeout: DioConfig.timeout,
      sendTimeout: DioConfig.timeout,
      receiveTimeout: DioConfig.timeout,
      contentType: 'application/json; charset=utf-8',
      headers: {
        //"user-agent": 'aimusic/com.aimusic/1.0.0/10010/zh-CN (iOS 12.3.2)'
        //
      },
    );

    Future<Response> _retry(RequestOptions requestOptions) async {
      final options = Options(
        method: requestOptions.method,
        headers: requestOptions.headers,
      );
      return dio.request(
        requestOptions.path,
        data: requestOptions.data,
        queryParameters: requestOptions.queryParameters,
        options: options,
      );
    }

    /// 请求拦截器 and 响应拦截机 and 错误处理
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (options, handler) async {
      print("\n================== 请求数据 ==========================");

      print("params = ${options.data}");

      String url = options.uri.toString();
      print("url = ${url}");

      var token = await Common.getStorageValue('token');
      var userAgent = await Common.getStorageValue('userAgent');
      options.headers = {
        ...options.headers,
        "user-agent": userAgent,
        // 'aimusic/com.hevenmuisic.smart/1.0.1/10010/zh-CN (iOS 18.0)',
        "token": token,
      };
      print("headers = ${options.headers}");
      var json = Common.mergeParams(options.data);
      json = jsonEncode(json);
      print(json);
      var sig = AESUtil.encryptAes(json.toString());

      options.data = {"data": base64UrlEncode(sig)}; //json; ;
      print(options.data);
      return handler.next(options);
    }, onResponse: (response, handler) async {
      print("\n================== 响应数据 ==========================");
      print("code =  ${response.statusCode}");

      print("\n ");

      if (!response.data['data'].isEmpty) {
        String data = AESUtil.decryptAes(response.data['data']);

        var url = response.requestOptions.path;
        response.data['data'] =
            !url.contains('/api/systems/13001') ? jsonDecode(data) : data;
      }

      if (response.data["status"] == 410 || response.statusCode == 410) {
        // 检查是否为410或401状态码
        await Common.removeStorageValue('token');
        // 尝试刷新token
        print('status============${response.data["status"]}');
        final newToken = await refreshToken();

        if (newToken != null) {
          // 更新dio实例的headers，添加新的token
          dio.options.headers['token'] = newToken;

          // 使用新token重试原先失败的请求
          final options = response.requestOptions;
          print(options);
          dio.options.headers['token'] = newToken; // 确保这次请求也携带了新的token
          return handler.resolve(await dio.fetch(options));
        }
      }
      print(response);
      handler.next(response);
    }, onError: (DioError e, handler) async {
      print("\n================== 错误响应数据 ======================");
      print("type = ${e.type}");
      print("message = ${e.message}");
      print("code = ${e.response?.statusCode}");
      print("\n");

      if (e.response?.statusCode == 401) {
        RequestOptions requestOptions = e.requestOptions;
        await refreshToken();
        final Response response = await _retry(requestOptions);
        return handler.resolve(response); // 返回新响应
      }
      return handler.next(e);
    }));
  }
  static post(url, data) {
    return DioRequest().dio.post(url, data: data);
  }

  // static get(url, {Map<String, dynamic> params = const {}}) {
  //   return DioRequest().dio.get(url, data: params);
  // }

  static Future<Response> get(String url, {Map<String, dynamic>? params}) {
    return DioRequest().dio.get(
          url,
          data: params, // 使用命名参数传递查询参数
        );
  }
}

//
login(params) async {
  var response = await DioRequest.post('/api/relation/10002', params);
  var json = jsonDecode(response.toString());
  return json['data'][0];
}

signApple(params) async {
  var response = await DioRequest.post('/api/relation/10001', params);
  var json = jsonDecode(response.toString());
  return json;
}

sendSms(params) async {
  var response = await DioRequest.post('/api/users/send-sms-code', params);
  // print(response.toString());
  // var response =
  //     await DioRequest.post('/api/users/generate-inner-code', params);
  return jsonDecode(response.toString());
}

phonelogin(params) async {
  var response = await DioRequest.post('/api/users/login', params);
  var json = jsonDecode(response.toString());
  return json;
}

tomusic(params) async {
  var response = await DioRequest.post('/api/ai-music/20001', params);
  return jsonDecode(response.toString());
}

recommend(params) async {
  var response = await DioRequest.get('/api/ai-music/21001', params: params);
  print('recommend----');
  return jsonDecode(response.toString());
}

mymusic(params) async {
  var response = await DioRequest.get('/api/ai-music/22001', params: params);
  return jsonDecode(response.toString());
}

getProfile(params) async {
  var response = await DioRequest.get('/api/users/get-profile', params: params);
  return jsonDecode(response.toString());
}

getGoodsList(params) async {
  var response = await DioRequest.get('/api/goods/goods-list', params: params);
  var json = jsonDecode(response.toString());

  return json['data'];
}

getConfig() async {
  var response = await DioRequest.get('/api/systems/12002', params: {});
  var json = jsonDecode(response.toString());
  return json['data'];
}

repurchase(params) async {
  var response =
      await DioRequest.post('/api/recharge/ai-music-restore', params);
  var json = jsonDecode(response.toString());
  return json;
}

verification(params) async {
  var response = await DioRequest.post('/api/recharge/ai-music', params);
  var json = jsonDecode(response.toString());

  return json;
}

getAgree(params) async {
  var response = await DioRequest.get('/api/systems/13001', params: params);
  var json = jsonDecode(response.toString());

  return json;
}

deleteUser(params) async {
  var response = await DioRequest.post('/api/users/delete-user', params);
  print(response);
  var json = jsonDecode(response.toString());

  return json;
}

// void main() async {
//   login().then((value) => print(value));
// }

refreshToken() async {
  print('-----_refreshToken');
  var uuid = await Common.getStorageValue('uuid');
  var loginResponse = await login({"uuid": uuid});
  var token = saveUser(loginResponse);
  return token;
  // UserModel userModel = UserModel.fromJson(loginResponse);
  // // print(userModel.uid);
  // // // 存储 Token 和 Uid
  // await Common.saveStorageValue('token', userModel.token);
  // await Common.saveStorageValue('uuid', userModel.uuid);
  // await Common.saveStorageValue('uid', userModel.uid);
}

saveUser(loginResponse) async {
  UserModel userModel = UserModel.fromJson(loginResponse);
  await Common.saveStorageValue('isTourist', userModel.isTourist.toString());
  await Common.saveStorageValue('token', userModel.token);
  await Common.saveStorageValue('uuid', userModel.uuid ?? '');
  await Common.saveStorageValue('uid', userModel.uid ?? '');
  return userModel.token;
}

delmusic(params) async {
  var response = await DioRequest.post('/api/ai-music/22002', params);
  return jsonDecode(response.toString());
}
